package vrp;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

import java.io.IOException;
import javax.jdo.PersistenceManager;
import javax.servlet.http.*;

import vrp.SOrder;
import vrp.SOrderItem;
import vrp.PMF;

public class SOrderItemDeleteServlet extends HttpServlet {

    public void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws IOException {

    	PersistenceManager pm = PMF.get().getPersistenceManager();
    	
    	long sorderID = Integer.parseInt(req.getParameter("sorder"));
    	long sorderItemID = Integer.parseInt(req.getParameter("sorderItem"));

    	try {
        	Key sorderKey = KeyFactory.createKey(SOrder.class.getSimpleName(), sorderID);
            SOrder sorder = pm.getObjectById(SOrder.class, sorderKey);
            SOrderItem sorderItem = null;
            for (SOrderItem oi : sorder.getSOrderItems()) {
            	if (oi.getKey().getId() == sorderItemID) {
            		sorderItem = oi;
            		break;
            	}
            }
            sorder.getSOrderItems().remove(sorderItem);
            pm.makePersistent(sorder);
        } finally {
            pm.close();
        }
        resp.sendRedirect("/sorderitems.jsp?sorder=" + sorderID);
    }
}